<template>
  <div class="approval-container">
    <div class="header">
      <h2>审批待办</h2>
    </div>
    
    <div class="search-filter-card">
      <el-form :model="searchForm" :inline="true" label-width="80px" class="search-form">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="申请单号">
              <el-input v-model="searchForm.applicationNo" placeholder="请输入申请单号" style="width: 180px" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产品名称">
              <el-select v-model="searchForm.productId" placeholder="请选择产品" @change="handleProductChange" style="width: 150px">
                <el-option label="全部" value="" />
                <el-option v-for="product in productList" :key="product.id" :label="product.name" :value="product.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="申请状态">
              <el-select v-model="searchForm.status" placeholder="请选择申请状态" style="width: 150px">
                <el-option label="全部" value="" />
                <el-option label="待平台审核" value="1" />
                <el-option label="待测试负责人审批" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="创建人">
              <el-input v-model="searchForm.createdBy" placeholder="请输入创建人" style="width: 150px" />
            </el-form-item>
          </el-col>
          <el-col :span="16" class="search-buttons">
            <el-button type="primary" @click="handleSearch" class="search-btn">搜索</el-button>
            <el-button @click="handleReset" class="reset-btn">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>
    
    <div class="table-card">
      <el-table :data="approvalList" style="width: 100%" v-loading="loading" element-loading-text="加载中">
        <el-table-column prop="applicationNo" label="申请单号" width="180" />
        <el-table-column prop="productName" label="产品名称" width="180" />
        <el-table-column prop="productVersionName" label="版本" width="120" />
        <el-table-column prop="createdByName" label="创建人" width="100" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column prop="status" label="状态" width="120">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleViewApplication(scope.row)" class="view-btn">查看</el-button>
            <template v-if="scope.row.status === 1 && hasRole('PLATFORM_ADMIN')">
              <el-button type="success" size="small" @click="handleApproveApplication(scope.row)" class="approve-btn">通过</el-button>
              <el-button type="danger" size="small" @click="handleRejectApplication(scope.row)" class="reject-btn">拒绝</el-button>
            </template>
            <template v-if="scope.row.status === 2 && hasRole('TEST_MANAGER')">
              <el-button type="success" size="small" @click="handleTestManagerApproveApplication(scope.row)" class="approve-btn">通过</el-button>
              <el-button type="danger" size="small" @click="handleTestManagerRejectApplication(scope.row)" class="reject-btn">拒绝</el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    
    <!-- 申请单详情弹窗 -->
    <el-dialog v-model="viewDialog" title="申请单详情" width="800px">
      <div v-if="currentApplication" class="application-detail">
        <div class="detail-section">
          <h4>基本信息</h4>
          <el-descriptions :column="1" border>
            <el-descriptions-item label="申请单号">{{ currentApplication.applicationNo }}</el-descriptions-item>
            <el-descriptions-item label="产品名称">{{ currentApplication.productName }}</el-descriptions-item>
            <el-descriptions-item label="版本">{{ currentApplication.productVersionName }}</el-descriptions-item>
            <el-descriptions-item label="测试类型">{{ currentApplication.testType }}</el-descriptions-item>
            <el-descriptions-item label="申请说明">{{ currentApplication.description }}</el-descriptions-item>
          </el-descriptions>
        </div>
        
        <div class="detail-section" v-if="currentApplication.platformAuditOpinion || currentApplication.testManagerAuditOpinion">
          <h4>审批信息</h4>
          <el-descriptions :column="1" border>
            <el-descriptions-item v-if="currentApplication.platformAuditOpinion" label="平台审核意见">{{ currentApplication.platformAuditOpinion }}</el-descriptions-item>
            <el-descriptions-item v-if="currentApplication.testManagerAuditOpinion" label="测试负责人审批意见">{{ currentApplication.testManagerAuditOpinion }}</el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive } from 'vue'
import { getApplicationList, getApplicationById, approveApplication, rejectApplication, testManagerApprove, testManagerReject } from '@/api/application'
import { getProductList, getProductVersions } from '@/api/product'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/store/modules/user'

export default {
  name: 'Approval',
  components: {},
  setup() {
    const userStore = useUserStore()
    const userInfo = userStore.userInfo
    
    // 搜索表单
    const searchForm = reactive({
      applicationNo: '',
      productId: '',
      status: '',
      createdBy: ''
    })
    
    // 产品列表
    const productList = ref([])
    
    // 版本列表
    const versionList = ref([])
    
    // 审批列表
    const approvalList = ref([])
    
    // 分页信息
    const pagination = reactive({
      current: 1,
      size: 10,
      total: 0
    })
    
    // 加载状态
    const loading = ref(false)
    
    // 是否初始加载
    const isInitialLoad = ref(true)
    
    // 详情弹窗显示状态
    const viewDialog = ref(false)
    
    // 当前查看的申请单
    const currentApplication = ref(null)
    
    // 获取产品列表
    const fetchProductList = async () => {
      try {
        const response = await getProductList()
        productList.value.push(...response.data || [])
      } catch (error) {
        console.error('获取产品列表失败:', error)
        // 静默处理错误，不显示提示信息
      }
    }
    
    // 获取版本列表
    const fetchVersionList = async (productId) => {
      try {
        const response = await getProductVersions(productId)
        versionList.value.splice(0, versionList.value.length)
        versionList.value.push(...response.data || [])
      } catch (error) {
        console.error('获取版本列表失败:', error)
        // 静默处理错误，不显示提示信息
      }
    }
    
    // 获取审批列表
    const fetchApprovalList = async (params = {}) => {
      try {
        loading.value = true
        
        // 构建查询参数，默认只查询待平台审核和待测试负责人审批的申请
        const queryParams = {
          page: params.page || pagination.current,
          pageSize: params.pageSize || pagination.size,
          applicationNo: searchForm.applicationNo,
          productId: searchForm.productId,
          status: searchForm.status || '1,2', // 默认查询待平台审核(1)和待测试负责人审批(2)的申请
          createdBy: searchForm.createdBy
        }
        
        const response = await getApplicationList(queryParams)
        
        approvalList.value.splice(0, approvalList.value.length)
        approvalList.value.push(...(response.data.records || []))
        
        pagination.current = response.data.current || 1
        pagination.size = response.data.size || 10
        pagination.total = response.data.total || 0
        
        // 如果没有数据且不是初始加载，显示友好提示
        if (approvalList.value.length === 0 && !loading.value && !isInitialLoad) {
          ElMessage.info('当前没有相关待办任务')
        }
        
        isInitialLoad = false
      } catch (error) {
        console.error('获取审批列表失败:', error)
        // 使用更友好的提示而不是错误提示
        if (!isInitialLoad) {
          ElMessage.info('暂无待审批任务')
        }
      } finally {
        loading.value = false
      }
    }
    
    // 获取申请单详情
    const fetchApplicationDetail = async (applicationId) => {
      try {
        const response = await getApplicationById(applicationId)
        currentApplication.value = response.data
      } catch (error) {
        console.error('获取申请单详情失败:', error)
        ElMessage.warning('获取申请单详情失败，请稍后重试')
      }
    }
    
    // 搜索
    const handleSearch = () => {
      pagination.current = 1
      fetchApprovalList()
    }
    
    // 重置
    const handleReset = () => {
      searchForm.applicationNo = ''
      searchForm.productId = ''
      searchForm.status = ''
      searchForm.createdBy = ''
      pagination.current = 1
      fetchApprovalList()
    }
    
    // 分页大小变更
    const handleSizeChange = (size) => {
      pagination.size = size
      fetchApprovalList()
    }
    
    // 当前页变更
    const handleCurrentChange = (current) => {
      pagination.current = current
      fetchApprovalList()
    }
    
    // 产品变更
    const handleProductChange = (productId) => {
      if (productId) {
        fetchVersionList(productId)
      } else {
        versionList.value.splice(0, versionList.value.length)
      }
    }
    
    // 查看申请单
    const handleViewApplication = async (row) => {
      await fetchApplicationDetail(row.id)
      viewDialog.value = true
    }
    
    // 平台审核通过申请单
    const handleApproveApplication = (row) => {
      ElMessageBox.prompt('请输入审核意见', '审核通过', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^.{0,200}$/,
        inputErrorMessage: '审核意见不超过200个字符'
      }).then(async ({ value }) => {
          try {
            const response = await approveApplication(row.id, {
              platformAuditOpinion: value
            })
            
            if (response.data.code === 200) {
              ElMessage.success('审核通过成功')
              fetchApprovalList()
            } else {
              ElMessage.warning(response.data.message || '审核通过失败')
            }
          } catch (error) {
            console.error('审核通过申请单失败:', error)
            ElMessage.warning('审核通过失败，请检查网络或稍后重试')
          }
        }).catch(() => {
          // 用户取消审核
        })
      }
    
    // 平台审核拒绝申请单
    const handleRejectApplication = (row) => {
      ElMessageBox.prompt('请输入拒绝原因', '审核拒绝', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^.{0,200}$/,
        inputErrorMessage: '拒绝原因不超过200个字符'
      }).then(async ({ value }) => {
          try {
            const response = await rejectApplication(row.id, {
              platformAuditOpinion: value
            })
            
            if (response.data.code === 200) {
              ElMessage.success('审核拒绝成功')
              fetchApprovalList()
            } else {
              ElMessage.warning(response.data.message || '审核拒绝失败')
            }
          } catch (error) {
            console.error('审核拒绝申请单失败:', error)
            ElMessage.warning('审核拒绝失败，请检查网络或稍后重试')
          }
        }).catch(() => {
          // 用户取消审核
        })
      }
    
    // 测试负责人审核通过申请单
    const handleTestManagerApproveApplication = (row) => {
      ElMessageBox.prompt('请输入审批意见和测试人员ID（多个ID用逗号分隔）\n例如: 同意,1,2,3', '审批通过', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^.+$/,
        inputErrorMessage: '请输入审批意见和测试人员ID'
      }).then(async ({ value }) => {
          try {
            const parts = value.split(',')
            const testManagerAuditOpinion = parts[0]
            const testerIds = parts.slice(1).join(',')
            
            const response = await testManagerApprove(row.id, {
              testManagerAuditOpinion,
              testerIds
            })
            
            if (response.data.code === 200) {
              ElMessage.success('审批通过成功')
              fetchApprovalList()
            } else {
              ElMessage.warning(response.data.message || '审批通过失败')
            }
          } catch (error) {
            console.error('审批通过申请单失败:', error)
            ElMessage.warning('审批通过失败，请检查网络或稍后重试')
          }
        }).catch(() => {
          // 用户取消审批
        })
      }
    
    // 测试负责人审核拒绝申请单
    const handleTestManagerRejectApplication = (row) => {
      ElMessageBox.prompt('请输入拒绝原因', '审批拒绝', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^.{0,200}$/,
        inputErrorMessage: '拒绝原因不超过200个字符'
      }).then(async ({ value }) => {
          try {
            const response = await testManagerReject(row.id, {
              testManagerAuditOpinion: value
            })
            
            if (response.data.code === 200) {
              ElMessage.success('审批拒绝成功')
              fetchApprovalList()
            } else {
              ElMessage.warning(response.data.message || '审批拒绝失败')
            }
          } catch (error) {
            console.error('审批拒绝申请单失败:', error)
            ElMessage.warning('审批拒绝失败，请检查网络或稍后重试')
          }
        }).catch(() => {
          // 用户取消审批
        })
      }
    
    // 获取状态文本
    const getStatusText = (status) => {
      switch (status) {
        case 1:
          return '待平台审核'
        case 2:
          return '待测试负责人审批'
        default:
          return '未知状态'
      }
    }
    
    // 获取状态标签类型
    const getStatusTagType = (status) => {
      switch (status) {
        case 1:
        case 2:
          return 'warning'
        default:
          return 'default'
      }
    }
    
    // 判断用户是否有指定角色
    const hasRole = (role) => {
      if (!userInfo || !userInfo.roles) return false
      return userInfo.roles.includes(role)
    }
    
    // 初始化
    const init = async () => {
      await fetchProductList()
      await fetchApprovalList()
    }
    
    // 组件挂载时初始化
    init()
    
    return {
      searchForm,
      productList,
      versionList,
      approvalList,
      pagination,
      loading,
      viewDialog,
      currentApplication,
      userInfo,
      handleSearch,
      handleReset,
      handleSizeChange,
      handleCurrentChange,
      handleProductChange,
      handleViewApplication,
      handleApproveApplication,
      handleRejectApplication,
      handleTestManagerApproveApplication,
      handleTestManagerRejectApplication,
      getStatusText,
      getStatusTagType,
      hasRole
    }
  }
}
</script>

<style scoped>
.approval-container {
  padding: 20px;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.header h2 {
  color: white;
  margin-bottom: 20px;
  font-size: 24px;
  font-weight: 600;
}

.search-filter-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  transition: box-shadow 0.3s ease;
}

.search-filter-card:hover {
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
}

.search-form {
  width: 100%;
}

.search-buttons {
  display: flex;
  justify-content: flex-end;
  align-items: flex-end;
}

.search-btn {
  background: linear-gradient(45deg, #667eea, #764ba2);
  border: none;
  margin-right: 10px;
  transition: all 0.3s ease;
}

.search-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.reset-btn {
  transition: all 0.3s ease;
}

.reset-btn:hover {
  transform: translateY(-2px);
}

.table-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  transition: box-shadow 0.3s ease;
}

.table-card:hover {
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
}

.el-table {
  border-radius: 8px;
  overflow: hidden;
}

.el-table th {
  background: linear-gradient(45deg, #f5f7fa, #e4e7ed);
  font-weight: 600;
  color: #303133;
}

.el-table tr:hover > td {
  background-color: #f5f7fa !important;
}

.el-table__row--striped td {
  background-color: #fafafa;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.application-detail {
  padding: 10px 0;
}

.detail-section {
  margin-bottom: 20px;
}

.detail-section h4 {
  margin-bottom: 15px;
  font-weight: 600;
  color: #303133;
}

.view-btn {
  margin-right: 10px;
  background: #409eff;
  border: none;
  transition: all 0.3s ease;
}

.view-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.4);
}

.approve-btn {
  margin-right: 10px;
  background: #67c23a;
  border: none;
  transition: all 0.3s ease;
}

.approve-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(103, 194, 58, 0.4);
}

.reject-btn {
  background: #f56c6c;
  border: none;
  transition: all 0.3s ease;
}

.reject-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(245, 108, 108, 0.4);
}

/* 输入框和选择框样式增强 - 确保显示边框线条 */
:deep(.el-input__wrapper) {
  box-shadow: none !important;
  border: 1px solid #dcdfe6 !important;
  border-radius: 6px;
}

:deep(.el-input__wrapper:hover) {
  border-color: #c0c4cc !important;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

:deep(.el-input__wrapper.is-focused) {
  border-color: #1890ff !important;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2) !important;
}

:deep(.el-select__wrapper) {
  box-shadow: none !important;
  border: 1px solid #dcdfe6 !important;
  border-radius: 6px;
}

:deep(.el-select__wrapper:hover) {
  border-color: #c0c4cc !important;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

:deep(.el-select__wrapper.is-focused) {
  border-color: #1890ff !important;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2) !important;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .approval-container {
    padding: 15px;
  }
  
  .search-filter-card,
  .table-card {
    padding: 15px;
  }
}

@media (max-width: 768px) {
  .approval-container {
    padding: 10px;
  }
  
  .header h2 {
    font-size: 20px;
  }
  
  .search-filter-card,
  .table-card {
    padding: 10px;
  }
  
  .search-form .el-col {
    margin-bottom: 10px;
  }
  
  .search-buttons {
    justify-content: center;
    margin-top: 10px;
  }
  
  .pagination-container {
    justify-content: center;
  }
}
</style>